
#include "log_sum_exp_tiling.h"
#include "register/op_def_registry.h"
#include "tiling/platform/platform_ascendc.h"
#include <math.h>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <algorithm>


namespace optiling {
    const uint32_t BLOCK_SIZE = 32;
static ge::graphStatus TilingFunc(gert::TilingContext* context)
{

    LogSumExpTilingData tiling;
    constexpr int32_t NUM = 5;
    const gert::StorageShape* x1_shape = context->GetInputShape(0);
    uint32_t sizeofdatatype;
    uint32_t totallengthAligned;
    auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo());
    auto socVersion = ascendcPlatform.GetSocVersion();
    uint64_t ub_size;
    ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub_size);
    uint32_t totallength = context->GetInputShape(0)->GetStorageShape().GetShapeSize();
    auto dt = context->GetInputDesc(0)->GetDataType();
    if(dt == ge::DT_INT8){
        sizeofdatatype = 1;
    }else if(dt == ge::DT_FLOAT16 || dt == ge::DT_BF16){
        sizeofdatatype = 2;
    }
    else if (dt == ge::DT_INT32) {
        sizeofdatatype = 4;
    }
    else{
        sizeofdatatype = 4;
    }

    uint32_t ALIGN_NUM = BLOCK_SIZE / sizeofdatatype;
    uint32_t tiling_size = ((ub_size) / BLOCK_SIZE / 2) / NUM;
    tiling_size = tiling_size <= 8 ? tiling_size : tiling_size / 8 * 8;
    uint32_t tilelength = tiling_size * ALIGN_NUM;
    tiling.set_tilelength(tilelength);

    int32_t dimnum = context->GetInputShape(0)->GetStorageShape().GetDimNum();
    int32_t lastdimnum = context->GetInputShape(0)->GetStorageShape().GetDim(dimnum - 1);
    tiling.set_lastdimnum(lastdimnum);

    // auto ptr = context->GetAttrs()->GetInt(0);
    // tiling.set_dim(*ptr);

    auto *dimlist = context->GetAttrs()->GetListInt(0);
    const int64_t *pdimlist = dimlist->GetData();
    int32_t dimlistsize = dimlist->GetSize();
    int32_t dim1 = *pdimlist;
    tiling.set_dim(dim1);
    
    int32_t dimlength = context->GetInputShape(0)->GetStorageShape().GetDim(dim1);
    uint32_t outputlength = totallength / dimlength;

    int32_t loopcount = totallength / lastdimnum;
    tiling.set_loopcount(loopcount);
    tiling.set_totallength(totallength);
    tiling.set_outputlength(outputlength);

    if(dim1 == -1 || dim1 == (dimnum - 1)) {
        if(lastdimnum <= tilelength) {
            context->SetTilingKey(1);
        } else {
            context->SetTilingKey(2);    //for long dim 
        }
    } else {
        if(lastdimnum <= tilelength) {
            context->SetTilingKey(3);     
        } else {
            context->SetTilingKey(4);    //for long dim 
        }
    }
    int32_t dim = (dim1 < 0) ? dimnum + dim1 : dim1;    
    auto tiling_key = context->GetTilingKey();
    int32_t v1stlevelloop = 0;
    int32_t v2ndlevleloop = 0;
    int32_t v1stlevelgap = 0;
    int32_t v2ndlevelgap = 0;
    int32_t v3rdlevleloop = 0;
    if(tiling_key == 3 || tiling_key == 4) {
        v1stlevelloop = 1;
        for(int32_t k = 0; k < dim; k++) {
            v1stlevelloop *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
        }
        v2ndlevleloop = context->GetInputShape(0)->GetStorageShape().GetDim(dim);
        v1stlevelgap = totallength / v1stlevelloop;
        v2ndlevelgap = 1;
        for(int32_t k = dim + 1; k < dimnum; k++) {
            v2ndlevelgap *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
        }
        v3rdlevleloop = 1;
        for(int32_t k = dim + 1; k < dimnum - 1; k++) {
            v3rdlevleloop *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
        }
    }
    // optimization 
    if(tiling_key == 3 || tiling_key == 4) {
        for(int32_t k = dimnum - 2; k > dim; k--) {
            if(lastdimnum * context->GetInputShape(0)->GetStorageShape().GetDim(k) < tilelength) {
                lastdimnum *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
                v3rdlevleloop = v3rdlevleloop / context->GetInputShape(0)->GetStorageShape().GetDim(k);
                tiling.set_lastdimnum(lastdimnum);
            }
        }    
    }
    //special case for dimsize = 1
    int32_t  dimsize = context->GetInputShape(0)->GetStorageShape().GetDim(dim);
    if(dimsize == 1) {
        context->SetTilingKey(5);
    }
    //specail case for lastdimnum is aligned
    int32_t connectnum = 1;
    if(tiling_key == 1) {
        if(lastdimnum % ALIGN_NUM == 0) {
            connectnum = tilelength / lastdimnum;
            if(connectnum > 1) {
                context->SetTilingKey(6);
                tiling.set_connectnum(connectnum);
            }
        }
    }     
    const gert::StorageShape* x_shape = context->GetInputShape(0);
    int32_t shapeNum = x_shape->GetStorageShape().GetDimNum();  
    int32_t stepGapPerAxis[64];
    int32_t axDirNumPerAxis[64];
    int32_t outterGapPerAxis[64];
    int32_t reduceLength = 1;
    int32_t axistmparr[64];
    int32_t loopgap = context->GetInputShape(0)->GetStorageShape().GetDim(shapeNum - 1);
    if(dimlistsize > 1) {
        // int32_t dim_1 = *pdimlist;
        // pdimlist += 1;
        // int32_t dim_2 = *pdimlist;
        // std::cout << "dim_1:" << dim_1 << std::endl;
        // std::cout << "dim_2:" << dim_2 << std::endl;
        for(int32_t k = 0; k < 64; k++) {
            axistmparr[k] = -800;
        }    
        for(int32_t k = 0; k < dimlistsize; k++) {
            int32_t axistmp = *pdimlist;
            pdimlist += 1;
            if(axistmp < 0) {
                axistmp += shapeNum;
            }    
            std::cout<< "axistmp:" << axistmp << std::endl;
            axistmparr[k] = axistmp;
        }    
        std::sort(axistmparr, axistmparr + dimlistsize);
        for(int32_t k = 0; k < dimlistsize; k++) {    
            int32_t axistmp = axistmparr[k];
            std::cout<< "axistmp:" << axistmp << std::endl;
            if(axistmp == shapeNum - 1) {            
                stepGapPerAxis[k] = 1;
                outterGapPerAxis[k] = x_shape->GetStorageShape().GetDim(axistmp);
            } else {
                int32_t tmp = 1;
                for(int32_t m = axistmp; m < shapeNum - 1; m++) {
                    tmp *= x_shape->GetStorageShape().GetDim(m + 1);
                }
                int32_t tmp2 = 1;
                for(int32_t m = axistmp; m < shapeNum; m++) {
                    tmp2 *= x_shape->GetStorageShape().GetDim(m);
                }
                stepGapPerAxis[k] = tmp;
                outterGapPerAxis[k] = tmp2;
            }
            axDirNumPerAxis[k] = x_shape->GetStorageShape().GetDim(axistmp);
            reduceLength *= axDirNumPerAxis[k];
            std::cout<< "stepGapPerAxis:" << stepGapPerAxis[k] << std::endl;
            std::cout<< "axDirNumPerAxis:" << axDirNumPerAxis[k] << std::endl;
            std::cout<< "outterGapPerAxis:" << outterGapPerAxis[k] << std::endl;
        }
        outputlength = totallength / reduceLength;
        if(axistmparr[dimlistsize - 1] == shapeNum - 1) {
            std::cout<< "contain last dim"  << std::endl;
            lastdimnum = context->GetInputShape(0)->GetStorageShape().GetDim(shapeNum - 1);
            tiling.set_lastdimnum(lastdimnum);
            context->SetTilingKey(901);
            int32_t tmpdimsize = dimlistsize - 2;
            for(int32_t t = shapeNum - 2;t >= 0; t--) {
                if(axistmparr[tmpdimsize] == t) {
                    loopgap *= x_shape->GetStorageShape().GetDim(t);
                    if(tmpdimsize >= 1) {
                        tmpdimsize -= 1;
                    } else {
                        t = -1;
                    }
                } else {
                    t = -1;
                }
            }
        } else {
            std::cout<< "not contain last dim"  << std::endl;
            lastdimnum = context->GetInputShape(0)->GetStorageShape().GetDim(shapeNum - 1);
            tiling.set_lastdimnum(lastdimnum);
            context->SetTilingKey(902);
            int32_t tmpdimsize = dimlistsize - 1;
            for(int32_t t = shapeNum - 2;t >= 0; t--) {
                if(axistmparr[tmpdimsize] == t) {
                    loopgap *= x_shape->GetStorageShape().GetDim(t);
                    if(tmpdimsize >= 1) {
                        tmpdimsize -= 1;
                    } else {
                        t = -1;
                    }
                } else {
                    t = -1;
                }
            }
        }        
    }
    tiling.set_axisDumNum(dimlistsize);
    tiling.set_stepGapPerAxis(stepGapPerAxis);
    tiling.set_axDirNumPerAxis(axDirNumPerAxis);
    tiling.set_outterGapPerAxis(outterGapPerAxis);
    tiling.set_loopgap(loopgap);
    tiling.set_outputlength(outputlength);
    tiling.set_lastdimnum(lastdimnum);

    tiling.set_v1stlevelloop(v1stlevelloop);
    tiling.set_v2ndlevleloop(v2ndlevleloop);
    tiling.set_v1stlevelgap(v1stlevelgap);
    tiling.set_v2ndlevelgap(v2ndlevelgap);
    tiling.set_v3rdlevleloop(v3rdlevleloop);
    std::cout << "tiling_key:" << context->GetTilingKey() << std::endl;
    std::cout << "shapeNum:" << shapeNum << std::endl;
    std::cout << "ALIGN_NUM:" << ALIGN_NUM << std::endl;
    std::cout << "dimnum:" << dimnum << std::endl;
    std::cout << "totallength:" << totallength << std::endl;
    std::cout << "outputlength:" << outputlength << std::endl;
    std::cout << "tilelength:" << tilelength << std::endl;
    std::cout << "dim_ptr:" << dim1 << std::endl;
    std::cout << "dimlistsize:" << dimlistsize << std::endl;
    std::cout << "lastdimnum:" << lastdimnum << std::endl;
    std::cout << "loopcount:" << loopcount << std::endl;
    std::cout << "v1stlevelloop:" << v1stlevelloop << std::endl;
    std::cout << "v2ndlevleloop:" << v2ndlevleloop << std::endl;
    std::cout << "v1stlevelgap:" << v1stlevelgap << std::endl;
    std::cout << "v2ndlevelgap:" << v2ndlevelgap << std::endl;
    std::cout << "v3rdlevleloop:" << v3rdlevleloop << std::endl;
    std::cout << "connectnum:" << connectnum << std::endl;
    std::cout << "loopgap:" << loopgap << std::endl;

    context->SetBlockDim(1);
    tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity());
    context->GetRawTilingData()->SetDataSize(tiling.GetDataSize());

    return ge::GRAPH_SUCCESS;
}
}


namespace ge {
static ge::graphStatus InferShape(gert::InferShapeContext* context)
{
    const gert::Shape* x1_shape = context->GetInputShape(0);
    gert::Shape* y_shape = context->GetOutputShape(0);
    *y_shape = *x1_shape;
    return GRAPH_SUCCESS;
}
}


namespace ops {
class LogSumExp : public OpDef {
public:
    explicit LogSumExp(const char* name) : OpDef(name)
    {
        this->Input("x")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Output("y")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Attr("dim").AttrType(OPTIONAL).ListInt({});
        this->Attr("keep_dim").AttrType(OPTIONAL).Bool(false);

        this->SetInferShape(ge::InferShape);

        this->AICore()
            .SetTiling(optiling::TilingFunc);
        this->AICore().AddConfig("ascend310b");

    }
};

OP_ADD(LogSumExp);
}
